﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Data;
using System.Web.UI.WebControls;
using NetDon.OA.Business.Sequentials;
using NetDon.OA.Data;
using NetDon.OA.Data.CollectionClasses;
using NetDon.OA.Data.DaoClasses;
using NetDon.OA.Data.EntityClasses;
using NetDon.OA.Data.HelperClasses;
using NetDon.OA.Data.Linq;
using NetDon.OA.Data.RelationClasses;
using NetDon.OA.Interface;
using NetDon.OA.Interface.Common;
using NetDon.OA.Interface.eLogistics;
using NetDon.Utilities;
using SD.LLBLGen.Pro.ORMSupportClasses;


namespace NetDon.OA.Business
{
    public class IssuingOrderService : IIssuingOrderService
    {

        public DataTable GetMachineAccountOrders(IssuingOrderSearchCriteria criteria, string sortExpression, SortDirection sortDirection, int pageSize, int pageIndex)
        {

            var fields = new EntityFields(14);
            var index = 0;
            fields[index++] = IssuingOrderFields.ShuntingCost.SetFieldAlias("DueShippingCost"); ;
            fields[index++] = new EntityField("TobePaidShippingCost", new ScalarQueryExpression(
                        MachineAccountPaymentFields.TobePaidShippingCost.SetAggregateFunction(AggregateFunction.Sum),
                         IssuingOrderFields.Id == MachineAccountPaymentFields.IssuingOrderId

                        ));
            fields[index++] = new EntityField("IncomeAmount", new ScalarQueryExpression(
                        MachineAccountIncomeFields.IncomeAmount.SetAggregateFunction(AggregateFunction.Sum),
                       IssuingOrderFields.Id == MachineAccountIncomeFields.IssuingOrderId));
            fields[index++] = new EntityField("DeductionExceptionsAmount", new ScalarQueryExpression(
                                                                               MachineAccountPaymentFields.
                                                                                   DeductionExceptionsAmount.
                                                                                   SetAggregateFunction(
                                                                                       AggregateFunction.Sum),
                                                                               IssuingOrderFields.Id == MachineAccountPaymentFields.IssuingOrderId));
            fields[index++] = new EntityField("PendingShippingCost", new Expression(
                fields[0],
                ExOp.Sub, fields[1]));
            //new EntityField("TotalSold", new ScalarQueryExpression(SalesItemFields.ProductId.SetAggregateFunction(AggregateFunction.Count), filterTotalSold)));

            fields[index++] = IssuingOrderFields.Id;
            fields[index++] = IssuingOrderFields.OrderCode;
            fields[index++] = CustomerInfoFields.CustomerName;
            fields[index++] = IssuingOrderFields.OrderStatus;
            fields[index++] = IssuingOrderFields.RouteTypeId;
            fields[index++] = IssuingOrderFields.TransportationPlanCode;
            fields[index++] = IssuingOrderFields.BusinessType;
            fields[index++] = IssuingOrderFields.ReceivingOrderDate;

            fields[index++] = IssuingOrderFields.ActualShippingDate;


            IEntityField sortField = null;
            switch (sortExpression)
            {
                case "TobePaidShippingCost":
                    sortField = fields[1];
                    break;
                case "Id":
                    sortField = IssuingOrderFields.Id;
                    break;
                case "OrderCode":
                    sortField = IssuingOrderFields.OrderCode;
                    break;
                case "CustomerName":
                    sortField = CustomerInfoFields.CustomerName;
                    break;
                case "OrderStatus":
                    sortField = IssuingOrderFields.OrderStatus;
                    break;
                case "RouteTypeId":
                    sortField = IssuingOrderFields.RouteTypeId;
                    break;
                case "TransportationPlanCode":
                    sortField = IssuingOrderFields.TransportationPlanCode;
                    break;
                case "BusinessType":
                    sortField = IssuingOrderFields.BusinessType;
                    break;
                case "ShuntingCost":
                    sortField = fields[0];
                    break;
                case "IncomeAmount":
                    sortField = fields[2];
                    break;
                case "DeductionExceptionsAmount":
                    sortField = fields[3];
                    break;
                case "PendingShippingCost":
                    sortField = fields[4];
                    break;
                case "DueShippingCost":
                    sortField = fields[0];
                    break;
                case "ReceivingOrderDate":
                    sortField = IssuingOrderFields.ReceivingOrderDate;
                    break;
                case "ActualShippingDate":
                    sortField = IssuingOrderFields.ActualShippingDate;
                    break;

            }
            SortExpression expression;
            if (sortField != null)
            {
                SortOperator sortOperator = sortDirection == SortDirection.Ascending
                                                ? SortOperator.Ascending
                                                : SortOperator.Descending;
                expression = new SortExpression((EntityField)sortField | sortOperator);
            }
            else
            {
                expression = new SortExpression(IssuingOrderFields.ActualShippingDate | SortOperator.Descending);
                expression.Add(IssuingOrderFields.ReceivingOrderDate | SortOperator.Descending);
                expression.Add(IssuingOrderFields.TransportationPlanCode | SortOperator.Descending);
            }


            var table = new DataTable();
            var dao = new TypedListDAO();
            dao.GetMultiAsDataTable(fields, table, 0, expression, GetSearchOrderPredicate(criteria),
                                    GetGetMachineAccountOrdersSearchRelations(), false, null, null, pageIndex + 1, pageSize);


            return table;
        }

        public int GetGetMachineAccountOrdersCount(IssuingOrderSearchCriteria criteria)
        {
            var collection = new IssuingOrderCollection();

            return collection.GetDbCount(GetSearchOrderPredicate(criteria), GetGetMachineAccountOrdersSearchRelations());
        }


        public int GetOrderCount(IssuingOrderSearchCriteria criteria)
        {
            var collection = new IssuingOrderCollection();

            return int.Parse(collection.GetScalar(IssuingOrderFieldIndex.Id, null, AggregateFunction.CountDistinct, GetSearchOrderPredicate(criteria), GetOrderSearchRelations(), null).ToString());


        }

        public DataTable SearchOrdersByCondition(IssuingOrderSearchCriteria criteria, string sortExpression, SortDirection sortDirection, int pageSize, int pageIndex)
        {
            var fields = new EntityFields(26);
            var index = 0;
            fields[index++] = IssuingOrderFields.ShuntingCost;


            //fields[index++] = new EntityField("UnitCost",
            //                                new Expression(IssuingOrderFields.ShuntingCost, ExOp.Div,   IssuingOrderDeliveryFields.ConvertedOrderVolumnWeight));



            fields[index++] = IssuingOrderFields.Id;
            fields[index++] = IssuingOrderFields.OrderCode;
            fields[index++] = CustomerInfoFields.CustomerName;
            fields[index++] = IssuingOrderFields.OrderStatus;
            fields[index++] = IssuingOrderFields.GoodsShippedTypeId;
            fields[index++] = IssuingOrderFields.RouteTypeId;
            fields[index++] = IssuingOrderFields.ReceivingOrderDate;
            fields[index++] = IssuingOrderFields.TransportationPlanCode;
            fields[index++] = IssuingOrderFields.OrderVehicleNumber;
            fields[index++] = IssuingOrderFields.OrderQuantity;
            fields[index++] = IssuingOrderFields.CheckoutType;
            fields[index++] = IssuingOrderFields.PlannedShippingDate;
            fields[index++] = IssuingOrderFields.ShuntingPerson;
            fields[index++] = IssuingOrderFields.PaymentMethod;
            fields[index++] = IssuingOrderFields.ActualShippingDate;

            fields[index++] = IssuingOrderFields.DelayedDays;
            fields[index++] = IssuingOrderFields.BusinessType;
            fields[index++] = IssuingOrderFields.OnsiteOperator;
            fields[index++] = IssuingOrderFields.StartShippmentDate;

            fields[index++] = IssuingOrderFields.GoodsLeftBoxAmount;
            fields[index++] = IssuingOrderFields.ActualEntruckingBoxAmount;
            fields[index++] = IssuingOrderFields.IsGoodsJilted;
            fields[index++] = IssuingOrderFields.LastUpdatedBy;
            fields[index++] = IssuingOrderFields.LastUpdatedDate;

            fields[index++] = UserFields.UserName;



            IEntityField sortField = null;
            switch (sortExpression)
            {
                case "ShuntingCost":
                    sortField = fields[0];
                    break;
                //case "UnitCost":
                //    sortField = fields[1];
                //    break;

                case "Id":
                    sortField = IssuingOrderFields.Id;
                    break;
                case "OrderCode":
                    sortField = IssuingOrderFields.OrderCode;
                    break;
                case "CustomerName":
                    sortField = CustomerInfoFields.CustomerName;
                    break;
                case "OrderStatus":
                    sortField = IssuingOrderFields.OrderStatus;
                    break;
                case "GoodsShippedTypeId":
                    sortField = IssuingOrderFields.GoodsShippedTypeId;
                    break;
                case "RouteTypeId":
                    sortField = IssuingOrderFields.RouteTypeId;
                    break;
                case "ReceivingOrderDate":
                    sortField = IssuingOrderFields.ReceivingOrderDate;
                    break;
                case "TransportationPlanCode":
                    sortField = IssuingOrderFields.TransportationPlanCode;
                    break;
                case "OrderVehicleNumber":
                    sortField = IssuingOrderFields.OrderVehicleNumber;
                    break;

                case "CheckoutType":
                    sortField = IssuingOrderFields.CheckoutType;
                    break;
                case "PlannedShippingDate":
                    sortField = IssuingOrderFields.PlannedShippingDate;
                    break;
                case "ShuntingPerson":
                    sortField = IssuingOrderFields.ShuntingPerson;
                    break;
                case "PaymentMethod":
                    sortField = IssuingOrderFields.PaymentMethod;
                    break;
                case "ActualShippingDate":
                    sortField = IssuingOrderFields.ActualShippingDate;
                    break;
                case "DelayedDays":
                    sortField = IssuingOrderFields.DelayedDays;
                    break;
                case "BusinessType":
                    sortField = IssuingOrderFields.BusinessType;
                    break;
                case "OnsiteOperator":
                    sortField = IssuingOrderFields.OnsiteOperator;
                    break;
                case "StartShippmentDate":
                    sortField = IssuingOrderFields.StartShippmentDate;
                    break;

                case "GoodsLeftBoxAmount":
                    sortField = IssuingOrderFields.GoodsLeftBoxAmount;
                    break;
                case "ActualEntruckingBoxAmount":
                    sortField = IssuingOrderFields.ActualEntruckingBoxAmount;
                    break;

                case "IsGoodsJilted":
                    sortField = IssuingOrderFields.IsGoodsJilted;
                    break;
                case "OrderQuantity":
                    sortField = IssuingOrderFields.OrderQuantity;
                    break;
                case "LastUpdatedDate":
                    sortField = IssuingOrderFields.LastUpdatedDate;
                    break;
                case "LastUpdatedBy":
                    sortField = IssuingOrderFields.LastUpdatedBy;
                    break;

            }
            SortExpression expression;
            if (sortField != null)
            {
                SortOperator sortOperator = sortDirection == SortDirection.Ascending
                                                ? SortOperator.Ascending
                                                : SortOperator.Descending;
                expression = new SortExpression((EntityField)sortField | sortOperator);
            }
            else
            {
                expression = new SortExpression(IssuingOrderFields.ReceivingOrderDate | SortOperator.Descending);
                expression.Add(IssuingOrderFields.OrderCode | SortOperator.Descending);
                expression.Add(IssuingOrderFields.TransportationPlanCode | SortOperator.Descending);
            }


            var table = new DataTable();
            var dao = new TypedListDAO();
            dao.GetMultiAsDataTable(fields, table, 0, expression, GetSearchOrderPredicate(criteria),
                                    GetOrderSearchRelations(), false, null, null, pageIndex + 1, pageSize);


            return table;
        }



        public string[] GetIssuingOrderAddress(string prefix, int count)
        {
            var metaData = new LinqMetaData();
            return
                metaData.IssuingOrderDelivery.Where(
                    order => order.DeliveryAddress.StartsWith(prefix, StringComparison.InvariantCultureIgnoreCase)).Take
                    (count).Select(order => order.DeliveryAddress).Distinct().ToArray();
        }

        public bool AddOrder(IssuingOrderData issuingOrderData)
        {
            var trans = new Transaction(IsolationLevel.ReadCommitted, "AddOrder");
            try
            {
                // Save Order
                AddOrder(issuingOrderData, trans);

                trans.Commit();
                AppendConfigData(issuingOrderData.RouteTypeId, issuingOrderData.DeliveryProvince, issuingOrderData.IssuingOrderDeliveryDataList);
                return true;
            }
            catch (Exception)
            {
                trans.Rollback();
                throw;
            }
        }



        public bool ModifyOrder(IssuingOrderData issuingOrderData)
        {
            var trans = new Transaction(IsolationLevel.ReadCommitted, "ModifyOrder");
            try
            {
                // Save Order
                ModifyOrder(issuingOrderData, trans);
                trans.Commit();
                AppendConfigData(issuingOrderData.RouteTypeId, issuingOrderData.DeliveryProvince, issuingOrderData.IssuingOrderDeliveryDataList);
                return true;
            }
            catch (Exception)
            {
                trans.Rollback();
                throw;
            }
        }

        public bool RemoveOrder(Guid orderId)
        {
            var trans = new Transaction(IsolationLevel.ReadCommitted, "RemoveOrder");
            try
            {

                //delete RevenueMachineAccountInvoiceReceipt
                var revenueMachineAccountCollection = new RevenueMachineAccountCollection();

                revenueMachineAccountCollection.DeleteMulti(RevenueMachineAccountFields.IssuingOrderId == orderId);

                //delete payment

                new MachineAccountPaymentCollection().DeleteMulti(MachineAccountPaymentFields.IssuingOrderId == orderId);
                new MachineAccountIncomeCollection().DeleteMulti(MachineAccountIncomeFields.IssuingOrderId == orderId);

                //delete receipt track
                var issuingOrderReceiptInfoTrackCollection = new IssuingOrderReceiptInfoTrackCollection();

                issuingOrderReceiptInfoTrackCollection.GetMulti(IssuingOrderReceiptInfoTrackFields.IssuingOrderId == orderId);
                foreach (var issuingOrderReceiptInfoTrack in issuingOrderReceiptInfoTrackCollection)
                {
                    new IssuingOrderReceiptInfoTrackCommentCollection().DeleteMulti(IssuingOrderReceiptInfoTrackCommentFields.IssuingOrderReceiptInfoTrackId == issuingOrderReceiptInfoTrack.Id);
                    issuingOrderReceiptInfoTrack.Delete();
                }

                //delete on way track
                var issuingOrderOnWayTrackCollection = new IssuingOrderOnWayTrackCollection();

                issuingOrderOnWayTrackCollection.GetMulti(IssuingOrderOnWayTrackFields.IssuingOrderId == orderId);
                foreach (var collection in issuingOrderOnWayTrackCollection)
                {
                    new IssuingOrderOnWayTrackCommentCollection().DeleteMulti(IssuingOrderOnWayTrackCommentFields.IssuingOrderOnWayTrackId == collection.Id);

                    new IssuingOrderOnWayTrackHistoryCollection().DeleteMulti(IssuingOrderOnWayTrackHistoryFields.IssuingOrderOnWayTrackId == collection.Id);
                    collection.Delete();
                }

                new IssuingOrderDeliveryCollection().DeleteMulti(IssuingOrderDeliveryFields.IssuingOrderId == orderId);


                new IssuingOrderVehicleInfoCollection().DeleteMulti(IssuingOrderVehicleInfoFields.IssuingOrderId == orderId);


                new IssuingOrderCollection().DeleteMulti(IssuingOrderFields.Id == orderId);


                return true;

            }
            catch (Exception)
            {
                trans.Rollback();
                throw;
            }
        }


        public IssuingOrderData GetIssuingOrder(Guid issuingOrderId)
        {
            return GetIssuingOrderData(new IssuingOrderEntity(issuingOrderId));
        }
        public IssuingOrderData GetIssuingOrderByOrderCode(string orderCode)
        {

            var metaData = new LinqMetaData();
            var issuingOrder =
                metaData.IssuingOrder.FirstOrDefault(order => order.OrderCode == orderCode);
            return GetSimpleIssuingOrderData(issuingOrder);
        }
        public bool ExistsIssuingOrderByTransportationPlanCode(Guid id, string transportationPlanCode)
        {
            if (id != Guid.Empty)
                return new LinqMetaData().IssuingOrder.Any(order => order.TransportationPlanCode == transportationPlanCode && order.Id != id);
            return new LinqMetaData().IssuingOrder.Any(order => order.TransportationPlanCode == transportationPlanCode);
        }

        public IssuingOrderData GetIssuingOrderByTransportationPlanCode(string transportationPlanCode)
        {

            var metaData = new LinqMetaData();
            var issuingOrder = metaData.IssuingOrder.FirstOrDefault(order => order.TransportationPlanCode == transportationPlanCode);
            return issuingOrder == null ? null : GetSimpleIssuingOrderData(issuingOrder);
        }

        public string[] GetIssuingOrderByOrderCode(string orderCode, int count)
        {

            var metaData = new LinqMetaData();
            return
                 metaData.IssuingOrder.Where(
                     order => order.OrderCode.StartsWith(orderCode, StringComparison.InvariantCultureIgnoreCase)).Take
                     (count).Select(order => orderCode).ToArray();
        }
        public IssuingOrderData GetSimpleIssuingOrder(Guid issuingOrderId)
        {
            return GetSimpleIssuingOrderData(new IssuingOrderEntity(issuingOrderId));
        }


        public bool RemoveIssuingOrderDelivery(Guid issuingOrderDeliveryId)
        {
            var trans = new Transaction(IsolationLevel.ReadCommitted, "RemoveIssuingOrderDelivery");
            try
            {

                var issuingOrderDeliveryEntity = new IssuingOrderDeliveryEntity(issuingOrderDeliveryId);
                trans.Add(issuingOrderDeliveryEntity);
                issuingOrderDeliveryEntity.Delete();

                trans.Commit();
                return true;
            }
            catch (Exception)
            {
                trans.Rollback();
                throw;
            }
        }

        public IssuingOrderDeliveryData GetIssuingOrderDelivery(Guid issuingOrderDeliveryId)
        {
            var issuingOrderDeliveryEntity = new IssuingOrderDeliveryEntity(issuingOrderDeliveryId);
            return GetIssuingOrderDeliveryData(issuingOrderDeliveryEntity);
        }

        public IEnumerable<IssuingOrderVehicleData> GetIssuingOrderVehicleInfo(Guid issuingOrderId)
        {
            var issuingOrderVehicles = new IssuingOrderVehicleInfoCollection();

            issuingOrderVehicles.GetMulti(IssuingOrderVehicleInfoFields.IssuingOrderId == issuingOrderId);
            return from issuingOrderVehicle in issuingOrderVehicles select GetIssuingOrderVehicleData(issuingOrderVehicle);


        }

        public IEnumerable<IssuingOrderDeliveryData> GetIssuingOrderDeliveryByOrderId(Guid issuingOrderId)
        {
            var issuingOrderDeliveries = new IssuingOrderDeliveryCollection();
            issuingOrderDeliveries.GetMulti(IssuingOrderDeliveryFields.IssuingOrderId == issuingOrderId);
            return from issuingOrderDelivery in issuingOrderDeliveries select GetIssuingOrderDeliveryData(issuingOrderDelivery);
        }


        public bool UpdateShuntingCost(Dictionary<Guid, decimal?> shuntingCosts)
        {
            var trans = new Transaction(IsolationLevel.ReadCommitted, "UpdateShuntingCost");
            try
            {
                foreach (var shuntingCost in shuntingCosts)
                {

                    if (shuntingCost.Value.HasValue)
                    {

                        var order = new IssuingOrderEntity(shuntingCost.Key);
                        order.ShuntingCost = shuntingCost.Value ?? 0;
                        trans.Add(order);
                        order.Save();
                    }

                }
            }
            catch (Exception)
            {
                return false;
            }

            return true;

        }

        public bool UpdateGoodsUnloadingCost(Transaction trans, Guid issuingOrderId, decimal goodsUnloadingCost)
        {

            try
            {

                var entity = new IssuingOrderEntity(issuingOrderId);
                entity.GoodsUnloadingCost = goodsUnloadingCost;
                trans.Add(entity);
                entity.Save();
                trans.Commit();
                return true;
            }
            catch (Exception)
            {
                trans.Rollback();
                throw;
            }

        }

        public bool ModifyOrderStatus(Guid issuingOrderId, OrderStatus orderStatus)
        {
            var trans = new Transaction(IsolationLevel.ReadCommitted, "ModifyOrderStatus");
            try
            {
                var order = new IssuingOrderEntity(issuingOrderId);
                order.OrderStatus = (int)orderStatus;
                trans.Add(order);
                order.Save();
                trans.Commit();

            }
            catch (Exception)
            {
                trans.Rollback();
                return false;
            }

            return true;
        }

        public bool ConfirmOrderClosure(Guid issuingOrderId)
        {
            var trans = new Transaction(IsolationLevel.ReadCommitted, "ConfirmOrderClosure");
            try
            {
                var order = new IssuingOrderEntity(issuingOrderId);
                order.OrderStatus = (int)OrderStatus.Closed;
                trans.Add(order);
                order.Save();
                //AddRevenueMachineAccount(order, trans);
                trans.Commit();

            }
            catch (Exception)
            {
                trans.Rollback();
                return false;
            }

            return true;
        }


        public bool CheckIsPaymentExist(Guid issuingOrderId)
        {
            var collection = new MachineAccountPaymentCollection();
            collection.GetMulti(MachineAccountPaymentFields.IssuingOrderId == issuingOrderId);
            return collection.Count > 0;
        }

        public bool AutoConfirmOrderClosure()
        {
            var trans = new Transaction(IsolationLevel.ReadCommitted, "AutoConfirmOrderClosure");
            try
            {

                var orders = new IssuingOrderCollection();
                orders.GetMulti(IssuingOrderFields.OrderStatus == (int)OrderStatus.ReceiptTrackComplted);
                foreach (var order in orders)
                {
                    var machineAccounts = new MachineAccountPaymentCollection();
                    machineAccounts.GetMulti(MachineAccountPaymentFields.IssuingOrderId ==
                                                                   order.Id);
                    var paidShippingCost = machineAccounts.Sum(m => m.TobePaidShippingCost);
                    if (order.ShuntingCost - paidShippingCost == 0)
                    {
                        order.OrderStatus = (int)OrderStatus.Closed;
                        trans.Add(order);
                        order.Save();
                        //AddRevenueMachineAccount(order, trans);
                    }
                }
                trans.Commit();

            }
            catch (Exception)
            {
                trans.Rollback();
                return false;
            }

            return true;
        }

        public decimal? GetUnitCost(Guid companyId, string deliveryCity, Guid? routeTypeId)
        {
            //
            var metaData = new LinqMetaData();
            var issuingOrder = metaData.IssuingOrderDelivery.FirstOrDefault(order => order.AreaId == companyId && order.DeliveryCity == deliveryCity && order.IssuingOrder.RouteTypeId == routeTypeId);
            if (issuingOrder != null && issuingOrder.UnitCost.HasValue)
            {
                return issuingOrder.UnitCost;
            }
            var service = ServiceContainer.GetService<IGoodsTravelDaysConfigService>();
            var goodsTravelConfigData = service.GetGoodsTravelDaysConfigDatasByCondition(new GoodsTravelDaysConfigSearchCriteria()
            {
                AreaId = companyId,
                DeliveryCity = deliveryCity,
                RouteTypeId = routeTypeId
            });
            if (goodsTravelConfigData != null)
            {
                return goodsTravelConfigData.UnitCost;
            }
            return 0;
        }


        public decimal? GetRevenueUnitCost(Guid companyId, string deliveryCity, Guid? routeTypeId)
        {
            //
            var metaData = new LinqMetaData();
            var issuingOrder = metaData.IssuingOrderDelivery.FirstOrDefault(order => order.AreaId == companyId && order.DeliveryCity == deliveryCity && order.IssuingOrder.RouteTypeId == routeTypeId);
            if (issuingOrder != null && issuingOrder.RevenueUnitCost.HasValue)
            {
                return issuingOrder.RevenueUnitCost;
            }
            var service = ServiceContainer.GetService<IGoodsTravelDaysConfigService>();
            var goodsTravelConfigData = service.GetGoodsTravelDaysConfigDatasByCondition(new GoodsTravelDaysConfigSearchCriteria()
            {
                AreaId = companyId,
                DeliveryCity = deliveryCity,
                RouteTypeId = routeTypeId
            });
            if (goodsTravelConfigData != null)
            {
                return goodsTravelConfigData.RevenueUnitCost;
            }
            return 0;
        }

        public bool ModifyIssuingOrderDeliveies(Guid routeTypeId, string delvieryProvince, IEnumerable<IssuingOrderDeliveryData> issuingOrderDeliveryDataList)
        {
            var trans = new Transaction(IsolationLevel.ReadCommitted, "ModifyIssuingOrderDeliveies");
            try
            {
                foreach (var issuingOrderDelivery in issuingOrderDeliveryDataList)
                {

                    var issuingOrderDeliveryEntity = new IssuingOrderDeliveryEntity(issuingOrderDelivery.Id);

                    GetIssuingOrderDeliveryEntity(issuingOrderDelivery, issuingOrderDeliveryEntity, issuingOrderEntity: null);

                    trans.Add(issuingOrderDeliveryEntity);
                    issuingOrderDeliveryEntity.Save();
                }

                AppendConfigData(routeTypeId, delvieryProvince, issuingOrderDeliveryDataList);
                trans.Commit();
                return true;
            }
            catch (Exception)
            {
                return false;
                trans.Rollback();

            }



        }


        #region Private provider
        private void AppendConfigData(Guid routeTypeId, string delvieryProvince, IEnumerable<IssuingOrderDeliveryData> issuingOrderDeliveryDataList)
        {

            //insert into goodTravelDayconfig and shunting cost
            foreach (var issuingOrderDeliveryData in issuingOrderDeliveryDataList)
            {
                ServiceContainer.GetService<IGoodsTravelDaysConfigService>().AppendGoodsTravelDaysConfig(issuingOrderDeliveryData.AreaId, routeTypeId, issuingOrderDeliveryData.DeliveryCity, delvieryProvince, issuingOrderDeliveryData.UnitCost, issuingOrderDeliveryData.RevenueUnitCost);
            }

        }
        private IRelationCollection GetGetMachineAccountOrdersSearchRelations()
        {
            var relation = new RelationCollection(IssuingOrderEntity.Relations.CustomerInfoEntityUsingCustomerId, JoinHint.Left);
            return relation;
        }

        private IRelationCollection GetOrderSearchRelations()
        {
            var relation = new RelationCollection(IssuingOrderEntity.Relations.CustomerInfoEntityUsingCustomerId, JoinHint.Left);
            relation.Add(IssuingOrderEntity.Relations.IssuingOrderDeliveryEntityUsingIssuingOrderId);
            relation.Add(new DynamicRelation(EntityType.IssuingOrderEntity, JoinHint.Left, EntityType.UserEntity, string.Empty, string.Empty,
                                             IssuingOrderFields.LastUpdatedBy == UserFields.UserId));
            return relation;
        }


        private void AddOrder(IssuingOrderData issuingOrderData, Transaction trans)
        {
            var issuingOrderEntity = new IssuingOrderEntity();
            GetIssuingOrderEntity(issuingOrderEntity, issuingOrderData);
            issuingOrderEntity.Id = issuingOrderData.Id;
            //assign order code
            issuingOrderEntity.OrderCode = Sequential.Generate(SequentialKeys.CustomerOrderCode,
                                                           new OrderCodeContext
                                                           {

                                                               CustomerCode =
                                                                   new CustomerInfoEntity(
                                                                   issuingOrderEntity.CustomerId.Value).
                                                                   CustomerCode
                                                           });

            trans.Add(issuingOrderEntity);
            issuingOrderEntity.Save();

            AddIssuingOrderDelivery(issuingOrderData, trans, issuingOrderEntity);
            AddIssuingOrderVehicleInfo(issuingOrderData, trans, issuingOrderEntity);

        }
        private void AddIssuingOrderDelivery(IssuingOrderData issuingOrderData, Transaction trans, IssuingOrderEntity issuingOrderEntity)
        {
            foreach (var issuingOrderDelivery in issuingOrderData.IssuingOrderDeliveryDataList)
            {

                var issuingOrderDeliveryEntity = new IssuingOrderDeliveryEntity(issuingOrderDelivery.Id);
                if (issuingOrderDeliveryEntity.IsNew)
                {
                    if (string.IsNullOrWhiteSpace(issuingOrderDelivery.DeliveryOrderCode))
                    {
                        continue;
                    }
                    issuingOrderDeliveryEntity.Id = Guid.NewGuid();

                }
                else
                {
                    if (string.IsNullOrWhiteSpace(issuingOrderDelivery.DeliveryOrderCode))
                    {
                        issuingOrderDeliveryEntity.Delete();
                        trans.Add(issuingOrderDeliveryEntity);
                        issuingOrderDeliveryEntity.Save();
                        DeleteReceiptTrackInfoTrack(issuingOrderDeliveryEntity, trans);
                        continue;
                    }
                }
                GetIssuingOrderDeliveryEntity(issuingOrderDelivery, issuingOrderDeliveryEntity, issuingOrderEntity);

                issuingOrderDeliveryEntity.IssuingOrderId = issuingOrderEntity.Id;
                trans.Add(issuingOrderDeliveryEntity);
                issuingOrderDeliveryEntity.Save();

            }
        }

        private void AddIssuingOrderVehicleInfo(IssuingOrderData issuingOrderData, Transaction trans, IssuingOrderEntity issuingOrderEntity)
        {

            if (issuingOrderData.OrderStatus == OrderStatus.Submitted)
            {
                if (issuingOrderData.OrderVehicleNumber > 0)
                {
                    //delete all firstly
                    DeleteIssuingOrderVehicleInfo(issuingOrderEntity, trans);
                    for (int i = 0; i < issuingOrderData.OrderVehicleNumber; i++)
                    {
                        var issuingOrderVehicleInfoEntity = new IssuingOrderVehicleInfoEntity();

                        GetIssuingOrderVehicleEntity(new IssuingOrderVehicleData() { AreaId = issuingOrderEntity.AreaId, IssuingOrderId = issuingOrderEntity.Id }, issuingOrderVehicleInfoEntity);
                        issuingOrderVehicleInfoEntity.Id = Guid.NewGuid();

                        trans.Add(issuingOrderVehicleInfoEntity);
                        issuingOrderVehicleInfoEntity.Save();
                    }
                }
            }
            if (issuingOrderData.IssuingOrderVehicleDataList != null && issuingOrderData.IssuingOrderVehicleDataList.Any())
            {
                foreach (var issuingOrderVehicleData in issuingOrderData.IssuingOrderVehicleDataList)
                {
                    var issuingOrderVehicleInfoEntity = new IssuingOrderVehicleInfoEntity(issuingOrderVehicleData.Id);
                    GetIssuingOrderVehicleEntity(issuingOrderVehicleData, issuingOrderVehicleInfoEntity);
                    trans.Add(issuingOrderVehicleInfoEntity);
                    issuingOrderVehicleInfoEntity.Save();

                }
            }
        }


        private void ModifyOrder(IssuingOrderData issuingOrderData, Transaction trans)
        {
            var issuingOrderEntity = new IssuingOrderEntity(issuingOrderData.Id);
            GetIssuingOrderEntity(issuingOrderEntity, issuingOrderData);
            trans.Add(issuingOrderEntity);
            issuingOrderEntity.Save();


            AddIssuingOrderDelivery(issuingOrderData, trans, issuingOrderEntity);
            AddIssuingOrderVehicleInfo(issuingOrderData, trans, issuingOrderEntity);
            AddOnWayTrackInfoTrack(issuingOrderEntity, trans);
        }

        private void DeleteIssuingOrderVehicleInfo(IssuingOrderEntity issuingOrderEntity, Transaction trans)
        {
            var collection = new IssuingOrderVehicleInfoCollection();
            trans.Add(collection);
            collection.DeleteMulti(IssuingOrderVehicleInfoFields.IssuingOrderId == issuingOrderEntity.Id);
        }
        private void AddOnWayTrackInfoTrack(IssuingOrderEntity issuingOrderEntity, Transaction trans)
        {
            if (issuingOrderEntity.OrderStatus == (int)OrderStatus.Entrucked)
            {
                //check
                var onwayTrackData =
               ServiceContainer.GetService<IIssuingOrderOnWayTrackService>().GetIssuingOrderOnWayTrackByIssuingOrderId(issuingOrderEntity.Id);
                if (onwayTrackData != null) return;

                var issuingOrderOnWayTrackEntity = new IssuingOrderOnWayTrackEntity()
                {
                    Id = Guid.NewGuid(),
                    IssuingOrderId = issuingOrderEntity.Id,
                    GoodsDelayedDays = 0,
                    IsGoodsDelayed = false,
                    IsGoodsExceptional = false,
                    CreatedDate = DateTime.Now,
                    LastUpdatedDate = DateTime.Now,
                    CreateBy = issuingOrderEntity.CreateBy,
                    LastUpdatedBy = issuingOrderEntity.LastUpdatedBy,
                    AreaId = issuingOrderEntity.AreaId,
                    GoodsTravelDaysUnit = (int)GoodsTravelDayUnit.Day
                };
                trans.Add(issuingOrderOnWayTrackEntity);
                issuingOrderOnWayTrackEntity.Save();
            }



        }
        private void DeleteReceiptTrackInfoTrack(IssuingOrderDeliveryEntity issuingOrderDeliveryEntity, Transaction trans)
        {

            var issuingOrderReceiptInfoTrackCollection = new IssuingOrderReceiptInfoTrackCollection();
            trans.Add(issuingOrderReceiptInfoTrackCollection);
            issuingOrderReceiptInfoTrackCollection.DeleteMulti(IssuingOrderReceiptInfoTrackFields.IssuingOrderDeliveryId == issuingOrderDeliveryEntity.Id & IssuingOrderReceiptInfoTrackFields.IssuingOrderId == issuingOrderDeliveryEntity.IssuingOrderId);

        }


        private IssuingOrderDeliveryEntity GetIssuingOrderDeliveryEntity(IssuingOrderDeliveryData issuingOrderDeliveryData, IssuingOrderDeliveryEntity issuingOrderDeliveryEntity, IssuingOrderEntity issuingOrderEntity = null)
        {

            issuingOrderDeliveryEntity.IssuingOrderId = issuingOrderDeliveryData.IssuingOrderId;
            issuingOrderDeliveryEntity.DeliveryOrderCode = issuingOrderDeliveryData.DeliveryOrderCode;

            issuingOrderDeliveryEntity.CreatedDate = issuingOrderDeliveryData.CreatedDate;
            issuingOrderDeliveryEntity.LastUpdatedBy = issuingOrderDeliveryData.LastUpdatedBy;
            issuingOrderDeliveryEntity.CreateBy = issuingOrderDeliveryData.CreateBy;
            issuingOrderDeliveryEntity.LastUpdatedDate = issuingOrderDeliveryData.LastUpdatedDate;
            issuingOrderDeliveryEntity.AreaId = issuingOrderDeliveryData.AreaId;
            issuingOrderDeliveryEntity.Remark = issuingOrderDeliveryData.Remark;
            issuingOrderDeliveryEntity.DeliveryOrderType = issuingOrderDeliveryData.DeliveryOrderType;
            issuingOrderDeliveryEntity.DeliveryAddress = issuingOrderDeliveryData.DeliveryAddress;
            issuingOrderDeliveryEntity.UnitCost = issuingOrderDeliveryData.UnitCost;
            issuingOrderDeliveryEntity.OrderQuantity = issuingOrderDeliveryData.OrderQuantity;
            issuingOrderDeliveryEntity.OrderVolumn = issuingOrderDeliveryData.OrderVolumn;
            issuingOrderDeliveryEntity.OrderWeight = issuingOrderDeliveryData.OrderWeight;
            issuingOrderDeliveryEntity.DeliveryCity = issuingOrderDeliveryData.DeliveryCity;

            issuingOrderDeliveryEntity.ActualEntruckingOrderQuantity =
                issuingOrderDeliveryData.ActualEntruckingOrderQuantity;
            issuingOrderDeliveryEntity.ActualEntruckingOrderVolumn =
                issuingOrderDeliveryData.ActualEntruckingOrderVolumn;
            issuingOrderDeliveryEntity.ActualEntruckingOrderWeight =
                issuingOrderDeliveryData.ActualEntruckingOrderWeight;
            issuingOrderDeliveryEntity.GoodsUnloadingPriceRatio = issuingOrderDeliveryData.GoodsUnloadingPriceRatio;
            issuingOrderDeliveryEntity.RevenueUnitCost = issuingOrderDeliveryData.RevenueUnitCost;

            if (issuingOrderEntity != null)
            {
                if (WebConfig.IsCalculateByWeight(issuingOrderEntity.GoodsShippedTypeId))
                {
                    issuingOrderDeliveryEntity.ConvertedOrderVolumnWeight = issuingOrderDeliveryData.OrderWeight;

                }
                else
                {
                    issuingOrderDeliveryEntity.ConvertedOrderVolumnWeight = issuingOrderDeliveryData.OrderVolumn;

                }

            }


            return issuingOrderDeliveryEntity;
        }
        private IssuingOrderDeliveryData GetIssuingOrderDeliveryData(IssuingOrderDeliveryEntity issuingOrderDeliveryEntity)
        {
            return new IssuingOrderDeliveryData()
                       {
                           Id = issuingOrderDeliveryEntity.Id,
                           IssuingOrderId = issuingOrderDeliveryEntity.IssuingOrderId,
                           DeliveryOrderCode = issuingOrderDeliveryEntity.DeliveryOrderCode,
                           Remark = issuingOrderDeliveryEntity.Remark,

                           CreatedDate = issuingOrderDeliveryEntity.CreatedDate,
                           LastUpdatedBy = issuingOrderDeliveryEntity.LastUpdatedBy,
                           CreateBy = issuingOrderDeliveryEntity.CreateBy,
                           LastUpdatedDate = issuingOrderDeliveryEntity.LastUpdatedDate,
                           AreaId = issuingOrderDeliveryEntity.AreaId,
                           DeliveryOrderType = issuingOrderDeliveryEntity.DeliveryOrderType,
                           DeliveryAddress = issuingOrderDeliveryEntity.DeliveryAddress,
                           DeliveryCity = issuingOrderDeliveryEntity.DeliveryCity,
                           UnitCost = issuingOrderDeliveryEntity.UnitCost,
                           OrderQuantity = issuingOrderDeliveryEntity.OrderQuantity,
                           OrderVolumn = issuingOrderDeliveryEntity.OrderVolumn,
                           OrderWeight = issuingOrderDeliveryEntity.OrderWeight,
                           ActualEntruckingOrderQuantity = issuingOrderDeliveryEntity.ActualEntruckingOrderQuantity,
                           ActualEntruckingOrderVolumn = issuingOrderDeliveryEntity.ActualEntruckingOrderVolumn,
                           ActualEntruckingOrderWeight = issuingOrderDeliveryEntity.ActualEntruckingOrderWeight,
                           GoodsUnloadingPriceRatio = issuingOrderDeliveryEntity.GoodsUnloadingPriceRatio,
                           RevenueUnitCost = issuingOrderDeliveryEntity.RevenueUnitCost,
                           DeliveryCityName = new CityEntity(issuingOrderDeliveryEntity.DeliveryCity).Name
                       };
        }

        private IssuingOrderVehicleInfoEntity GetIssuingOrderVehicleEntity(IssuingOrderVehicleData issuingOrderVehicleData, IssuingOrderVehicleInfoEntity issuingOrderVehicleInfoEntity)
        {

            issuingOrderVehicleInfoEntity.IssuingOrderId = issuingOrderVehicleData.IssuingOrderId;

            issuingOrderVehicleInfoEntity.AreaId = issuingOrderVehicleData.AreaId;
            issuingOrderVehicleInfoEntity.CarSharingPrice = issuingOrderVehicleData.CarSharingPrice;
            issuingOrderVehicleInfoEntity.DriverAppointedDate = issuingOrderVehicleData.DriverAppointedDate;
            issuingOrderVehicleInfoEntity.DriverDelayedHours = issuingOrderVehicleData.DriverDelayedHours;
            issuingOrderVehicleInfoEntity.DriverDelayedReasons = issuingOrderVehicleData.DriverDelayedReasons;
            issuingOrderVehicleInfoEntity.DriverName = issuingOrderVehicleData.DriverName;
            issuingOrderVehicleInfoEntity.DriverOnboardDate = issuingOrderVehicleData.DriverOnboardDate;
            issuingOrderVehicleInfoEntity.DriverTelephone = issuingOrderVehicleData.DriverTelephone;

            issuingOrderVehicleInfoEntity.VehicleNumber = issuingOrderVehicleData.VehicleNumber;
            issuingOrderVehicleInfoEntity.VechicleModel = issuingOrderVehicleData.VechicleModel;


            return issuingOrderVehicleInfoEntity;
        }
        private IssuingOrderVehicleData GetIssuingOrderVehicleData(IssuingOrderVehicleInfoEntity issuingOrderVehicleInfoEntity)
        {
            return new IssuingOrderVehicleData()
            {
                Id = issuingOrderVehicleInfoEntity.Id,
                IssuingOrderId = issuingOrderVehicleInfoEntity.IssuingOrderId,

                AreaId = issuingOrderVehicleInfoEntity.AreaId,
                CarSharingPrice = issuingOrderVehicleInfoEntity.CarSharingPrice,
                DriverAppointedDate = issuingOrderVehicleInfoEntity.DriverAppointedDate,
                DriverDelayedHours = issuingOrderVehicleInfoEntity.DriverDelayedHours,
                DriverDelayedReasons = issuingOrderVehicleInfoEntity.DriverDelayedReasons,
                DriverName = issuingOrderVehicleInfoEntity.DriverName,
                DriverOnboardDate = issuingOrderVehicleInfoEntity.DriverOnboardDate,
                DriverTelephone = issuingOrderVehicleInfoEntity.DriverTelephone,
                VechicleModel = issuingOrderVehicleInfoEntity.VechicleModel,

                VehicleNumber = issuingOrderVehicleInfoEntity.VehicleNumber,

            };
        }
        private IssuingOrderData GetSimpleIssuingOrderData(IssuingOrderEntity issuingOrderEntity)
        {
            var issuingOrderData = new IssuingOrderData()
            {
                Id = issuingOrderEntity.Id,
                BusinessType = (BusinessType)Enum.Parse(typeof(BusinessType), issuingOrderEntity.BusinessType.ToString()),
                AreaId = issuingOrderEntity.AreaId,
                CheckoutType = (CheckoutType)Enum.Parse(typeof(CheckoutType), issuingOrderEntity.CheckoutType.ToString()),
                CustomerId = issuingOrderEntity.CustomerId,
                DeliveryProvince = issuingOrderEntity.DeliveryProvince,
                GoodsShippedTypeId = issuingOrderEntity.GoodsShippedTypeId,
                TransportationPlanCode = issuingOrderEntity.TransportationPlanCode,
                OrderCode = issuingOrderEntity.OrderCode,
                OrderVolumn = issuingOrderEntity.OrderVolumn,
                ActualOrderVolumn = issuingOrderEntity.IssuingOrderDelivery.Sum(i => i.ActualEntruckingOrderVolumn),
                OrderWeight = issuingOrderEntity.OrderWeight,
                ActualOrderWeight = issuingOrderEntity.IssuingOrderDelivery.Sum(i => i.ActualEntruckingOrderWeight),
                OrderQuantity = issuingOrderEntity.OrderQuantity,
                ActualOrderQuantity = issuingOrderEntity.IssuingOrderDelivery.Sum(i => i.ActualEntruckingOrderQuantity),
                OrderStatus = (OrderStatus)Enum.Parse(typeof(OrderStatus), issuingOrderEntity.OrderStatus.ToString()),
                OrderVehicleNumber = issuingOrderEntity.OrderVehicleNumber,
                ReceivingOrderDate = issuingOrderEntity.ReceivingOrderDate,
                RouteTypeId = issuingOrderEntity.RouteTypeId,
                ShuntingCost = issuingOrderEntity.ShuntingCost,
                ActualShippingDate = issuingOrderEntity.ActualShippingDate,
                GoodsUnloadingCost = issuingOrderEntity.GoodsUnloadingCost,
                ActualEntruckingBoxAmount = issuingOrderEntity.ActualEntruckingBoxAmount,


            };

            issuingOrderData.DeliveryCity = issuingOrderEntity.IssuingOrderDelivery.Aggregate(issuingOrderData.DeliveryCity ?? string.Empty, (a, b) => a + b.DeliveryCity + ",").TrimEnd(new char[] { ',' });

            //原纸
            if (WebConfig.IsCalculateByWeight(issuingOrderEntity.GoodsShippedTypeId))
            {
                issuingOrderData.UnitCost = issuingOrderEntity.ShuntingCost / issuingOrderEntity.IssuingOrderDelivery.Sum(o => o.OrderWeight);


            }
            else
            {
                issuingOrderData.UnitCost = issuingOrderEntity.ShuntingCost / issuingOrderEntity.IssuingOrderDelivery.Sum(o => o.OrderVolumn);

            }


            return issuingOrderData;
        }

        private IssuingOrderData GetIssuingOrderData(IssuingOrderEntity issuingOrderEntity)
        {
            var issuingOrderData = new IssuingOrderData()
                       {
                           Id = issuingOrderEntity.Id,

                           ActualEntruckingBoxAmount = issuingOrderEntity.ActualEntruckingBoxAmount,
                           ActualShippingDate = issuingOrderEntity.ActualShippingDate,
                           BusinessType = (BusinessType)Enum.Parse(typeof(BusinessType), issuingOrderEntity.BusinessType.ToString()),
                           AreaId = issuingOrderEntity.AreaId,

                           CheckoutType = (CheckoutType)Enum.Parse(typeof(CheckoutType), issuingOrderEntity.CheckoutType.ToString()),

                           CreateBy = issuingOrderEntity.CreateBy,
                           CreatedDate = issuingOrderEntity.CreatedDate,
                           CustomerId = issuingOrderEntity.CustomerId,
                           CustomerCode = issuingOrderEntity.CustomerInfo.CustomerCode,
                           CustomerName = issuingOrderEntity.CustomerInfo.CustomerName,
                           DelayedDays = issuingOrderEntity.DelayedDays,
                           DelayedReasons = issuingOrderEntity.DelayedReasons,
                           ShuntingCost = issuingOrderEntity.ShuntingCost,
                           DeliveryProvince = issuingOrderEntity.DeliveryProvince,
                           GoodsUnloadingCost = issuingOrderEntity.GoodsUnloadingCost,
                           EntruckingAddress = issuingOrderEntity.EntruckingAddress,
                           EntruckingAddressName = issuingOrderEntity.EntruckingAddress.HasValue ? string.Empty : new DictionaryEntity(issuingOrderEntity.EntruckingAddress.Value).Name,
                           EntruckingDetails = issuingOrderEntity.EntruckingDetails,
                           GoodsJiltedReasons = issuingOrderEntity.GoodsJiltedReasons,
                           GoodsLeftBoxAmount = issuingOrderEntity.GoodsLeftBoxAmount,
                           GoodsShippedTypeId = issuingOrderEntity.GoodsShippedTypeId,
                           GoodsShippedTypeName = new DictionaryEntity(issuingOrderEntity.GoodsShippedTypeId).Name,
                           IsGoodsJilted = issuingOrderEntity.IsGoodsJilted,
                           LastUpdatedBy = issuingOrderEntity.LastUpdatedBy,
                           LastUpdatedDate = issuingOrderEntity.LastUpdatedDate,
                           OnsiteEntruckingComments = issuingOrderEntity.OnsiteEntruckingComments,
                           OnsiteOperator = issuingOrderEntity.OnsiteOperator,
                           OrderCode = issuingOrderEntity.OrderCode,
                           OrderStatus = (OrderStatus)Enum.Parse(typeof(OrderStatus), issuingOrderEntity.OrderStatus.ToString()),
                           OrderVehicleNumber = issuingOrderEntity.OrderVehicleNumber,
                           OrderVolumn = issuingOrderEntity.OrderVolumn,
                           ActualOrderVolumn = issuingOrderEntity.IssuingOrderDelivery.Sum(i => i.ActualEntruckingOrderVolumn),
                           OrderWeight = issuingOrderEntity.OrderWeight,
                           ActualOrderWeight = issuingOrderEntity.IssuingOrderDelivery.Sum(i => i.ActualEntruckingOrderWeight),
                           OrderQuantity = issuingOrderEntity.OrderQuantity,
                           ActualOrderQuantity = issuingOrderEntity.IssuingOrderDelivery.Sum(i => i.ActualEntruckingOrderQuantity),
                           PaymentMethod = issuingOrderEntity.PaymentMethod,
                           PlannedShippingDate = issuingOrderEntity.PlannedShippingDate,
                           ReceivingOrderDate = issuingOrderEntity.ReceivingOrderDate,
                           RouteTypeId = issuingOrderEntity.RouteTypeId,
                           RouteTypeName = new RouteEntity(issuingOrderEntity.RouteTypeId).RouteName,
                           ShuntingPerson = issuingOrderEntity.ShuntingPerson,
                           TransportationPlanCode = issuingOrderEntity.TransportationPlanCode,
                           ShuntingCostExceptionComment = issuingOrderEntity.ShuntingCostExceptionsComment,
                           StartShippmentDate = issuingOrderEntity.StartShippmentDate,
                           IsShuntingCostException = !string.IsNullOrWhiteSpace(issuingOrderEntity.ShuntingCostExceptionsComment),
                           IsClientReturnVisit = issuingOrderEntity.IsClientReturnVisit ?? false,
                           ClientTelephone = issuingOrderEntity.ClientTelephone,



                       };

            issuingOrderData.DeliveryCity = issuingOrderEntity.IssuingOrderDelivery.Aggregate(issuingOrderData.DeliveryCity ?? string.Empty, (a, b) => a + b.DeliveryCity + ",").TrimEnd(new char[] { ',' });



            //原纸
            if (WebConfig.IsCalculateByWeight(issuingOrderEntity.GoodsShippedTypeId))
            {
                issuingOrderData.UnitCost = issuingOrderEntity.ShuntingCost / issuingOrderEntity.IssuingOrderDelivery.Sum(o => o.OrderWeight);

            }
            else
            {
                issuingOrderData.UnitCost = issuingOrderEntity.ShuntingCost / issuingOrderEntity.IssuingOrderDelivery.Sum(o => o.OrderVolumn);

            }


            return issuingOrderData;
        }
        private IssuingOrderEntity GetIssuingOrderEntity(IssuingOrderEntity issuingOrderEntity, IssuingOrderData issuingOrder)
        {
            issuingOrderEntity.OrderVolumn = issuingOrder.OrderVolumn;
            issuingOrderEntity.OrderWeight = issuingOrder.OrderWeight;
            ;
            issuingOrderEntity.OrderQuantity = issuingOrder.OrderQuantity;


            issuingOrderEntity.ActualEntruckingBoxAmount = issuingOrder.ActualEntruckingBoxAmount;
            issuingOrderEntity.ActualShippingDate = issuingOrder.ActualShippingDate;
            issuingOrderEntity.BusinessType = (int)issuingOrder.BusinessType;
            issuingOrderEntity.AreaId = issuingOrder.AreaId;
            issuingOrderEntity.ShuntingCost = issuingOrder.ShuntingCost;
            issuingOrderEntity.CheckoutType = (int)issuingOrder.CheckoutType;
            issuingOrderEntity.CreateBy = issuingOrder.CreateBy;
            issuingOrderEntity.CreatedDate = issuingOrder.CreatedDate;
            issuingOrderEntity.CustomerId = issuingOrder.CustomerId;
            issuingOrderEntity.DelayedDays = issuingOrder.DelayedDays;
            issuingOrderEntity.DelayedReasons = issuingOrder.DelayedReasons;

            issuingOrderEntity.DeliveryProvince = issuingOrder.DeliveryProvince;

            issuingOrderEntity.EntruckingAddress = issuingOrder.EntruckingAddress;
            issuingOrderEntity.EntruckingDetails = issuingOrder.EntruckingDetails;
            issuingOrderEntity.GoodsJiltedReasons = issuingOrder.GoodsJiltedReasons;
            issuingOrderEntity.GoodsLeftBoxAmount = issuingOrder.GoodsLeftBoxAmount;
            issuingOrderEntity.GoodsShippedTypeId = issuingOrder.GoodsShippedTypeId;

            issuingOrderEntity.IsGoodsJilted = issuingOrder.IsGoodsJilted;
            issuingOrderEntity.LastUpdatedBy = issuingOrder.LastUpdatedBy;
            issuingOrderEntity.LastUpdatedDate = issuingOrder.LastUpdatedDate;

            issuingOrderEntity.OnsiteEntruckingComments = issuingOrder.OnsiteEntruckingComments;
            issuingOrderEntity.OnsiteOperator = issuingOrder.OnsiteOperator;
            issuingOrderEntity.OrderCode = issuingOrder.OrderCode;

            issuingOrderEntity.OrderStatus = (int)issuingOrder.OrderStatus;
            issuingOrderEntity.OrderVehicleNumber = issuingOrder.OrderVehicleNumber;


            issuingOrderEntity.PaymentMethod = issuingOrder.PaymentMethod;
            issuingOrderEntity.PlannedShippingDate = issuingOrder.PlannedShippingDate;
            issuingOrderEntity.ReceivingOrderDate = issuingOrder.ReceivingOrderDate;
            issuingOrderEntity.RouteTypeId = issuingOrder.RouteTypeId;

            issuingOrderEntity.ShuntingPerson = issuingOrder.ShuntingPerson;
            issuingOrderEntity.TransportationPlanCode = issuingOrder.TransportationPlanCode;
            issuingOrderEntity.ShuntingCostExceptionsComment = issuingOrder.ShuntingCostExceptionComment;
            issuingOrderEntity.StartShippmentDate = issuingOrder.StartShippmentDate;
            issuingOrderEntity.GoodsUnloadingCost = issuingOrder.GoodsUnloadingCost;

            issuingOrderEntity.IsClientReturnVisit = issuingOrder.IsClientReturnVisit;
            issuingOrderEntity.ClientTelephone = issuingOrder.ClientTelephone;

            return issuingOrderEntity;
        }
        private IPredicate GetSearchOrderPredicate(IssuingOrderSearchCriteria criteria)
        {
            var expression = new PredicateExpression();


            if (criteria.AreaId.HasValue && criteria.AreaId.Value != Guid.Empty)
            {
                expression.Add(IssuingOrderFields.AreaId == criteria.AreaId);
            }
            if (criteria.OrderStatus.HasValue)
            {
                expression.Add(IssuingOrderFields.OrderStatus == criteria.OrderStatus);
            }
            if (criteria.BusinessType.HasValue)
            {
                expression.Add(IssuingOrderFields.BusinessType == criteria.BusinessType);
            }

            if (!string.IsNullOrEmpty(criteria.OrderCode))
            {
                expression.Add(IssuingOrderFields.OrderCode % ("%" + criteria.OrderCode + "%"));
            }
            if (criteria.CustomerId.HasValue && criteria.CustomerId.Value != Guid.Empty)
            {
                expression.Add(IssuingOrderFields.CustomerId == criteria.CustomerId);
            }


            if (criteria.RouteTypeId.HasValue && criteria.RouteTypeId.Value != Guid.Empty)
            {
                expression.Add(IssuingOrderFields.RouteTypeId == criteria.RouteTypeId);
            }
            if (criteria.GoodsShippedTypeId.HasValue && criteria.GoodsShippedTypeId.Value != Guid.Empty)
            {
                expression.Add(IssuingOrderFields.GoodsShippedTypeId == criteria.GoodsShippedTypeId);
            }

            if (!string.IsNullOrEmpty(criteria.TransportationPlanCode))
            {
                expression.Add(IssuingOrderFields.TransportationPlanCode % ("%" + criteria.TransportationPlanCode + "%"));
            }

            if (criteria.CheckoutType.HasValue)
            {
                expression.Add(IssuingOrderFields.CheckoutType == criteria.CheckoutType);
            }
            if (criteria.IsGoodsJited.HasValue)
            {
                expression.Add(IssuingOrderFields.IsGoodsJilted == criteria.IsGoodsJited);
            }
            if (criteria.EntruckingAddress.HasValue && criteria.EntruckingAddress.Value != Guid.Empty)
            {
                expression.Add(IssuingOrderFields.EntruckingAddress == criteria.EntruckingAddress);
            }

            if (criteria.PaymentMethod.HasValue && criteria.PaymentMethod.Value != Guid.Empty)
            {
                expression.Add(IssuingOrderFields.PaymentMethod == criteria.PaymentMethod);
            }
            if (criteria.ShuntingPerson.HasValue && criteria.ShuntingPerson.Value != Guid.Empty)
            {
                expression.Add(IssuingOrderFields.ShuntingPerson == criteria.ShuntingPerson);
            }
            if (criteria.OnsiteOperator.HasValue && criteria.OnsiteOperator.Value != Guid.Empty)
            {
                expression.Add(IssuingOrderFields.OnsiteOperator == criteria.OnsiteOperator);
            }


            if (criteria.ReceivingOrderDate != null)
            {
                if (criteria.ReceivingOrderDate.Start.HasValue)
                {
                    expression.Add(IssuingOrderFields.ReceivingOrderDate >= criteria.ReceivingOrderDate.Start);
                }
                if (criteria.ReceivingOrderDate.End.HasValue)
                {
                    expression.Add(IssuingOrderFields.ReceivingOrderDate <= criteria.ReceivingOrderDate.End);
                }
            }

            if (criteria.PlannedShippingDate != null)
            {
                if (criteria.PlannedShippingDate.Start.HasValue)
                {
                    expression.Add(IssuingOrderFields.PlannedShippingDate >= criteria.PlannedShippingDate.Start);
                }
                if (criteria.PlannedShippingDate.End.HasValue)
                {
                    expression.Add(IssuingOrderFields.PlannedShippingDate <= criteria.PlannedShippingDate.End);
                }
            }
            if (criteria.ActualShippingDate != null)
            {
                if (criteria.ActualShippingDate.Start.HasValue)
                {
                    expression.Add(IssuingOrderFields.ActualShippingDate >= criteria.ActualShippingDate.Start);
                }
                if (criteria.ActualShippingDate.End.HasValue)
                {
                    expression.Add(IssuingOrderFields.ActualShippingDate <= criteria.ActualShippingDate.End);
                }
            }
            if (criteria.StartShippmentDate != null)
            {
                if (criteria.StartShippmentDate.Start.HasValue)
                {
                    expression.Add(IssuingOrderFields.StartShippmentDate >= criteria.StartShippmentDate.Start);
                }
                if (criteria.StartShippmentDate.End.HasValue)
                {
                    expression.Add(IssuingOrderFields.StartShippmentDate <= criteria.StartShippmentDate.End);
                }
            }

            if (!string.IsNullOrWhiteSpace(criteria.DeliveryProvince))
            {
                expression.Add(IssuingOrderFields.DeliveryProvince == criteria.DeliveryProvince);
            }
            if (!string.IsNullOrWhiteSpace(criteria.DeliveryCity))
            {
                expression.Add(IssuingOrderDeliveryFields.DeliveryCity == criteria.DeliveryCity);

            }
            if (!string.IsNullOrWhiteSpace(criteria.DeliveryOrderCode))
            {
                expression.Add(IssuingOrderDeliveryFields.DeliveryOrderCode % ("%" + criteria.DeliveryOrderCode + "%"));
            }
            return expression;
        }
        #endregion
    }
}
